﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.U2D;

/// <summary>
/// 从图集中获取一个 sprite 然后设置给 image
/// </summary>
//[ExecuteInEditMode]
[AddComponentMenu("UI/Behavior/AtlasFrame")]
public class UIAtlasFrame : MonoBehaviour
{


    public SpriteAtlas atlas;
    public Sprite defaultSprite;
    [Tooltip("icon_*  可以获取 icon_1, icon_3 的帧图名和 index")]
    public string atlasNameTemplate = "*";

    public bool lockedSize = false;


    [HideInInspector]
    [Tooltip("索引模式，启用后可以使用模板名称字符来设置 index")]
    public bool indexMode = false;
    private bool afterAwake = false;

    [HideInInspector]
    private int _index = 0;
    [HideInInspector]
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            if (value < 0) value = 0;
            if (value > this.indexMax) value = this.indexMax;
            this._index = value;
            this.frameName = this.GetNameFromTemplate(value);
            _index = value;
        }
    }

    [HideInInspector]
    public int indexMax = 99999;

    [HideInInspector]
    private string _frameName = "";

    [HideInInspector]
    public string frameName
    {
        get
        {
            return _frameName;
        }
        set
        {
            ResetImageSprite(value);
            _frameName = value;

        }
    }

    //editor 中预览修改的值 无法保存序列化，有bug
    //todo 将 AtlasFrame 改为动态使用的图集的脚本组件 而非 editor 中使用的组件来避免问题
    //主要提供的还是运行时的功能
    // #if UNITY_EDITOR
    // private void OnValidate()
    // {
    //     afterAwake = false;
    //     if(this.enabled)ResetImageSprite(this._index);
    // }
    // #endif

    // Start is called before the first frame update
    private void Awake()
    {
        this.afterAwake = true;
    }

    private string ResetImageSprite(string name)
    {
        var frame = atlas.GetSprite(name);
        if (frame == null && defaultSprite)
        {
            frame = defaultSprite;
            this._index = 0;
            return frame.name;
        }

        GetComponent<Image>().sprite = frame;
        if (frame && afterAwake)
        {
            var rect = GetComponent<Image>().rectTransform;
            if (!lockedSize) GetComponent<Image>().SetNativeSize();
            return frame.name;
        }

        return "";

    }

    private string GetNameFromTemplate(int index)
    {
        return atlasNameTemplate.Replace("*", index.ToString());
    }

    public void SetRandomIndex(int min, int max)
    {
        index = Random.Range(min, max);
    }

    public void SetRandomFrameName()
    {
        int index = Random.Range(0, atlas.spriteCount);
        Sprite[] sprites = new Sprite[atlas.spriteCount];
        atlas.GetSprites(sprites);
        if (index >= atlas.spriteCount) index = atlas.spriteCount - 1;
        frameName = sprites[index].name.Replace("(Clone)", "");
    }



}
